package keter.web.handler;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.ConstraintViolationException;

import keter.exception.KeterLoginException;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.SimpleMappingExceptionResolver;

import com.google.common.collect.Maps;

/**
 * <p>
 * Class : keter.web.handler.KeterExceptionHandler
 * <p>
 * Descdription: 运行时异常全部被捕获
 * 
 * @author gulixing@msn.com
 * @version 1.0.0
 */
public class KeterExceptionResolver extends SimpleMappingExceptionResolver {
	/**
	 * Logger for this class
	 */
	private static final Logger logger = LoggerFactory.getLogger(KeterExceptionResolver.class);

	@Override
	public ModelAndView resolveException(HttpServletRequest request,
			HttpServletResponse response, Object handler, Exception ex) {

		logger.error("系统异常：", ex);
		response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);

		String s = (String) request.getParameter("showerror");
		if (s!=null && s.equals("true")) {// 页面需要自定义异常
			return customEx(ex);
		}
		if(ex instanceof KeterLoginException){
		    Map<String, Exception> map = Maps.newHashMap();
		    map.put("ex", ex);
		    return new ModelAndView("/login?error=1");
		}

		else if( isAjax(request) ) {// JSON格式返回
			try {
				PrintWriter writer = response.getWriter();
				writer.write("error:'"+ex.getMessage()+"'");
				writer.flush();
			} catch (IOException e) {
				logger.error("",e);
			}
		}
		
		return new ModelAndView("/framework/errors/error");
	}

	private boolean isAjax(HttpServletRequest request) {
		return request.getHeader("accept").indexOf("application/json") > -1 || (request
				.getHeader("X-Requested-With") != null && request.getHeader(
				"X-Requested-With").indexOf("XMLHttpRequest") > -1);
	}

	private ModelAndView customEx(Exception ex) {
//		ConstraintViolationException cve = new ConstraintViolationException(null);
		// cve.get

		Map<String, String> map = Maps.newHashMap();
		String message = ex.getMessage();
		String cause = ex.getCause() != null ? ex.getCause().toString() : "";
		map.put("message", message);
		map.put("cause", cause);
		return new ModelAndView("/framework/errors/showerror", map);
	}

	public static void main(String[] args) {
		ModelAndView mav = new ModelAndView();
		System.out.println(mav.isEmpty());
	}

}
